/*
 * @lc app=leetcode.cn id=230 lang=cpp
 *
 * [230] 二叉搜索树中第K小的元素
 */

#include <limits.h>

#include <iostream>
#include <map>
#include <queue>
#include <set>
#include <stack>
#include <vector>
using namespace std;

struct TreeNode {
    int val;
    TreeNode *left;
    TreeNode *right;
    TreeNode() : val(0), left(nullptr), right(nullptr) {}
    TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
    TreeNode(int x, TreeNode *left, TreeNode *right)
        : val(x), left(left), right(right) {}
};

// @lc code=start
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left),
 * right(right) {}
 * };
 */
class Solution {
   public:
    int kthSmallest(TreeNode *root, int k) {
        vector<int> value;
        stack<TreeNode *> tree;

        // 中序遍历，将结果保存在 value 中
        while (value.size() < k) {
            // 寻找最左子节点
            while (root != nullptr) {
                tree.push(root);
                root = root->left;
            }

            // 访问当前节点
            root = tree.top();
            tree.pop();
            value.push_back(root->val);

            // 下一轮循环访问该节点的右子树
            root = root->right;
        }

        return value[k - 1];
    }
};
// @lc code=end
